<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Posts extends Admin_Controller {

	public $model = "post";
	public $view = "posts";
	var $theme_data = array(
		'layout_main' => 'layout',
		'left' => 'include/leftcp',
		);
	
	public $permissionCreate = 'Posts.Create';
	public $permissionDelete = 'Posts.Delete';
	public $permissionEdit   = 'Posts.Edit';
	public $permissionView   = 'Posts.View';
	public $current_permission   = 'Posts';
	
	protected $index_show = array(
		array( 'field' => 'post_title',
			'label' => 'Tiêu đề'),
				'custom_value' => '<a href="{url_edit}{post_id}">{post_title}</a>', //replace value	
				array( 'field' => 'post_title',
					'label' => 'Đăng - Xem',
					)
				);
	
	function __construct() {
		parent::__construct();
		$this->load->model($this->model.'_m',$this->model);
		$this->load->model('log_post_audit_m');
		$this->load->model('term_m');
		$this->url_index = admin_url() . $this->view;
		$this->folder_upload = $this->view."/";
		$this->url_edit = $this->url_index . "/edit/";
		$this->url_delete = $this->url_index . "/delete/";
		$this->url_add = $this->url_index . "/edit/0";
		$this->_model = $this->{$this->model};
		$this->data['config']['ajax']['url'] = $this->url_index.'/ajax_datatable_full';
	}

	function index($post_status = 1) {

		$this->data['post_status'] = $post_status;
		$action_info = $this->post->get_info_status($post_status);
		if($action_info && $view = $action_info['theme'])
		{
			$this->current_permission = $action_info['permission']['view'];
			$this->auth->restrict($this->current_permission);
			switch ($this->data['post_status']) {
				case 0:
				$this->data['up_title'] = 'Gửi tin';
				$this->data['down_title'] = '';
				break;
				case 1:
				$this->data['up_title'] = '';
				$this->data['down_title'] = 'Hạ tin xuống';
				break;
				case 2:
				$this->data['up_title'] = 'Duyệt tin';
				$this->data['down_title'] = 'Trả lại tin';
				break;
				case 3:
				$this->data['up_title'] = 'Đăng tin';
				$this->data['down_title'] = 'Trả lại tin';
				break;
				case 4:
					// $this->data['up_title'] = 'Đăng tin';
					// $this->data['down_title'] = 'Trả về tin nháp';
					// break;
				case 5:
				$this->data['up_title'] = 'Đăng tin';
				$this->data['down_title'] = 'Trả về nháp';
				break;
				case 6:
				$this->data['up_title'] = 'Gửi tin';
				$this->data['down_title'] = 'Trả về nháp';
				break;

				case 7:
				$this->data['up_title'] = 'Gửi tin';
				$this->data['down_title'] = 'Trả về nháp';
				break;
				
				default:
				$this->data['up_title'] = '';
				$this->data['down_title'] = '';
				break;
			}
			$this->data['menu_tree'] = $this->term_m->get_menu(0, 'category');
			$this->log_activity->add('Xem danh sách '.$action_info['title'], '','success');
			$this->theme_data["main"] = $this->view . $view;
			$this->template->viewAdmin($this->theme_data, $this->data);
		}
		else
		{
			$this->log_activity->add('Xem danh sách tin status = '.$post_status, '','error');
			show_404();
		}
		
	}

	function create() {
		$this->current_permission = $this->permissionCreate;
		$this->auth->restrict($this->current_permission);
		$post = $this->_model->get_by('post_status', 8);
		if(!$post)
		{
			$post_id = $this->_model->insert(array(
				'admin_id' => $this->admin->id,
				'post_status' =>8
				));
				$metas = array();
				$metas['_cms_post_author'] = $this->admin->account;
				$metas['_cms_post_date_create'] = time();
				foreach($metas as $_key => $_val)
					$this->{$this->model}->update_post_meta($post_id, $_key, $_val);
		}
		else
		{
			$post_id = $post->post_id;
		}
		redirect($this->url_edit.''.$post_id);
	}
	
	function edit($edit_id = 0) {
		$this->load->model('term_posts_m', 'term_posts');
		$post = $this->input->post();

		$edit_data = $this->{$this->model}->get_post($edit_id);
		//prd($post);
		if(!$this->_model->post_edit_check_permission($edit_data,$edit_id))
		{
			$this->load->library('user_agent');
			if($this->agent->referrer())
			{
				redirect($this->agent->referrer());
			}
			redirect($this->url_index.'/index/0');
		}
		//prd($post['edit']);
		if ($post && isset($post['edit'])) {

			//Kiểm tra xem có nhấn quay về hay không, nếu có thì unlock bài viết
			if(isset($post['edit_back']))
			{
				//set unlock post
				$this->_model->metapost_edit_lock($edit_id, 'set_unlock');
				redirect($this->url_index.'/index/'.$post['edit_back']);
			}

			$post_status = $post['edit']['post_status'];
			//kiểm tra quyền submit
			$permission = $this->post->get_info_status($post_status, 'permission');


			if($post['post_time_start'])
				$post['edit']['post_time_start'] = strtotime($post['post_time_start']);
			else
				$post['edit']['post_time_start'] = time();

			$post['metas']['_cms_post_editby'] = $this->admin->account;
			
			$post['metas']['_cms_post_royalties'] = str_replace(array(',','.'),'',$post['metas']['_cms_post_royalties']);

			if($post['edit']['post_slug'] == '')
				$post['edit']['post_slug'] = create_slug($post['edit']['post_title']);
			$post['edit']['post_excerpt'] = str_replace("\n", "<br>", $post['edit']['post_excerpt']);
			$post['metas']['_cms_post_date_update'] = time();

			//save audio content
			$post_content_audio = array();
			foreach($post['audio_src'] as $k => $src) {
				$post_content_audio[] = array(
					'file' => $src,
					'caption' => $post['audio_caption'][$k]
				);
			}
			$post['edit']['post_content_audio'] = maybe_serialize($post_content_audio);

			//save video content
			$post_content_video = array();
			foreach($post['video_src'] as $k => $src) {
				$post_content_video[] = array(
					'file' => $src,
					'caption' => $post['video_caption'][$k]
				);
			}
			$post['edit']['post_content_video'] = maybe_serialize($post_content_video);

			if($edit_id > 0)
			{
				$this->auth->restrict($permission['edit']);
				$this->{$this->model}->update($edit_id, $post['edit'], TRUE);
				$this->messages->add('Cập nhật thành công.','success');
			}
			else
			{

				$this->auth->restrict($permission['create']);
				// $post['edit']['post_date'] = time();
				$post['edit']['admin_id'] = $this->admin->id;
				$edit_id = $this->{$this->model}->insert($post['edit']);
				$this->messages->add('Thêm mới thành công.','success');
			}

			if(!isset($post['terms']))
				$post['terms'] = array();

			$this->term_posts->wp_set_post_terms($edit_id, $post['terms'],'category');

			if(isset($post['term_event']))
				$this->term_posts->wp_set_post_terms($edit_id, (array)$post['term_event'],'event');

			if(isset($post['metas'])) {
				foreach($post['metas'] as $_key => $_val)
					$this->{$this->model}->update_post_meta($edit_id, $_key, $_val);
			}
			//prd($post);
			redirect($this->url_edit . $edit_id);
		} //end process post

		/**
		 * Format video
		 * array(
		 * 		array(
		 * 			'id' => int 0
		 * 			'type' => string {youtube, googlevideo, }
		 * 			'url' => string
		 * 		),
		 * 		array(
		 * 			'id' => int 0
		 * 			'type' => string {youtube, googlevideo, }
		 * 			'url' => string
		 * 		)
		 * )
		 */
		$edit_data->post_content_audio = maybe_unserialize($edit_data->post_content_audio);
		$edit_data->post_content_video = maybe_unserialize($edit_data->post_content_video);

		$post_metas = $this->{$this->model}->get_post_meta($edit_id);
		$post_metas = format_meta_key($post_metas);
		//prd(format_meta_key($post_metas));

		if(!empty($post_metas['_cms_post_related_content'])) {
			$post_metas['_cms_post_related_content'] = $this->{$this->model}->where_in('post_id', $post_metas['_cms_post_related_content'])->get_all();
		}

		if(!empty($post_metas['_cms_post_most_read'])) {
			$post_metas['_cms_post_most_read'] = $this->{$this->model}->where_in('post_id', $post_metas['_cms_post_most_read'])->get_all();
		}

		if(!empty($post_metas['_cms_post_event_flow'])) {
			$post_metas['_cms_post_event_flow'] = $this->{$this->model}->where_in('post_id', $post_metas['_cms_post_event_flow'])->get_all();
		}
		
		$this->data['edit'] = $edit_data;
		@$this->data['edit']->post_excerpt = str_replace('<br>', "\n", $this->data['edit']->post_excerpt);
		$this->data['post_metas'] = $post_metas;

		$this->data['terms'] = $this->term_posts->get_the_terms($edit_id, 'category');
		$term_event_id = $this->term_posts->get_the_terms($edit_id,'event');
		$this->data['term_event_id'] = (($term_event_id && is_array($term_event_id))? end($term_event_id) :0 );
		
		$this->load->model('term_m', 'term');
		$this->data['post'] = $post;
		$this->data['edit_id'] = $edit_id;
		$this->data['menu_tree'] = $this->term->get_menu(0, 'category');
		$this->data['menu_events'] = $this->term->get_menu(0, 'event');

		if(isset($edit_data))
		{
			$this->current_permission = $this->post->get_info_status($edit_data->post_status, 'permission_view');
			$this->heading = $this->post->get_info_status($edit_data->post_status, 'title');
			$this->breadcrumbs->push('Sửa bài viết '.$edit_data->post_title, '/',30);
			//set lock post
			$this->_model->metapost_edit_lock($edit_id, 'set_lock');
		}
		else
		{
			$this->current_permission = 'Posts.Create';
			$this->heading = 'Tạo bài viết mới';
		}

		$this->theme_data["main"] = $this->view."/edit";
		$this->template->viewAdmin($this->theme_data, $this->data);
	}

	function change_status($edit_id, $status,$type ='up', $ajax = 0) {
		$new_status = $this->post->get_post_status_change($status, $type);
		$permission = $this->post->get_info_status($new_status, 'permission_edit');
		if(has_permission($permission))
		{
			$this->{$this->model}->update($edit_id, array('post_status' => $new_status), TRUE);
			$this->log_post_audit_m->post_change_status($edit_id, $type,$status,$new_status);
			if(!$ajax) {
				$this->messages->add('Cập nhật thành công.','success');
				redirect($this->url_edit . $edit_id);
			} else {
				die(true);
			}
		}
		else
		{
			if(!$ajax) {
				$this->messages->add('Bạn không có quyền thực hiện việc này.','error');
			}
			else
			{
				die('Bạn không có quyền thực hiện việc này.');
			}
		}
		
		
	}
	public function sendlist()
	{
		$this->data['post_status'] = -1;
		$this->current_permission = 'Posts.Sendlist';
		$this->auth->restrict($this->current_permission);
		$this->data['up_title'] = '';
		$this->data['down_title'] = '';
		
		$this->data['config']['ajax']['url'] = $this->url_index . '/sendlist';
		if($this->input->post())
		{
			$search = $this->input->post('search');
			$keyword = $this->input->post('keyword');
			$cat_id = $this->input->post('cat_id');
			$cat_id_sub = array();
			if($cat_id && $cat_id >0)
			{
				$subs = $this->term_m->get_menu_array($cat_id);
				$cat_id_sub = array_keys($subs);
				$cat_id_sub[] = $cat_id;
			}
			$this->data['posts'] = $this->{$this->model}->where('admin_id',$this->admin->id)->get_posts(array(
				'post_status' => array(2,3,6),
				'offset' => $this->input->post('start'),
				'posts_per_page' => $this->input->post('length'),
				'orderby'          => 'post_title',
				'category'          => $cat_id_sub,
				'search'	=> @$search['value']
				));
			$condition = array();
			if(isset($search['value']) && $search['value'] != '')
				$condition['post_title'] = $search['value'];

		 	if($cat_id && $cat_id >0)
				$condition['category'] = $cat_id_sub;

			$condition['search'] = @$search['value'];
		 

			$this->data['total_post'] = $this->{$this->model}->where('admin_id',$this->admin->id)->where_in('post_status', array(2,3,6))->num($condition);
				$this->ajax_datatable_full();
			die();
		}
		$this->theme_data["main"] = $this->view . '/index';
		$this->template->viewAdmin($this->theme_data, $this->data);
	}

	public function scheduled()
	{
		$this->data['post_status'] = -1;
		$this->current_permission = 'Posts.Scheduledlist';
		$this->auth->restrict($this->current_permission);
		$this->data['up_title'] = '';
		$this->data['down_title'] = '';
		
		$this->data['config']['ajax']['url'] = $this->url_index . '/scheduled';
		if($this->input->post())
		{
			$search = $this->input->post('search');
			$keyword = $this->input->post('keyword');
			$cat_id = $this->input->post('cat_id');
			$cat_id_sub = array();
			if($cat_id && $cat_id >0)
			{
				$subs = $this->term_m->get_menu_array($cat_id);
				$cat_id_sub = array_keys($subs);
				$cat_id_sub[] = $cat_id;
			}
			$this->data['posts'] = $this->{$this->model}->where('post_time_start >', time())->get_posts(array(
				'post_status' => 1,
				'offset' => $this->input->post('start'),
				'posts_per_page' => $this->input->post('length'),
				'orderby'          => 'post_title',
				'category'          => $cat_id_sub,
				'search'	=> @$search['value']
				));
			$condition = array();
			if(isset($search['value']) && $search['value'] != '')
				$condition['post_title'] = $search['value'];

		 	if($cat_id && $cat_id >0)
				$condition['category'] = $cat_id_sub;

			$condition['search'] = @$search['value'];
		 

			$this->data['total_post'] = $this->{$this->model}->where('post_time_start >', time())->where_in('post_status', array(1))->num($condition);
				$this->ajax_datatable_full();
			die();
		}
		$this->theme_data["main"] = $this->view . '/index';
		$this->template->viewAdmin($this->theme_data, $this->data);
	}

	function ajax_datatable_full()
	{
		$this->load->model('term_m', 'term');
		$post_status = $this->input->post('status');
		$search = $this->input->post('search');
		$cat_id = $this->input->post('cat_id');
		$keyword = $this->input->post('keyword');
		$cat_id_sub = array();
		if($cat_id && $cat_id >0)
		{
			$subs = $this->term_m->get_menu_array($cat_id);
			$cat_id_sub = array_keys($subs);
			$cat_id_sub[] = $cat_id;
		}
		if(isset($this->data['posts']))
		{
			$posts = $this->data['posts'];
		}
		else
		{
			$posts = $this->{$this->model}->condition_query_post_status($post_status)->get_posts(array(
				'offset' => $this->input->post('start'),
				'posts_per_page' => $this->input->post('length'),
				'category'          => $cat_id_sub,
				'search'	=> @$search['value']
				));
		}
		
		$render['sql'] = $this->db->last_query();
		
		foreach($posts as $k=>$post) {
			$cat = $this->term->get($post->cat_id);
			$posts[$k]->post_category = @$cat->term_name;
			$posts[$k]->post_title = the_excerpt($post->post_title, 50);
			$posts[$k]->date_create = $this->{$this->model}->get_post_meta($post->post_id, '_cms_post_date_create', true);
			$posts[$k]->author = $this->{$this->model}->get_post_meta($post->post_id, '_cms_post_author', true); // get author id created the post
			$posts[$k]->editby = $this->{$this->model}->get_post_meta($post->post_id, '_cms_post_editby', true); // get user id edited the post

			//get post lock status
			$lock = $this->_model->metapost_edit_lock($post->post_id, 'get');
			$posts[$k]->lockby = '';
			if($lock  && $lock->locktime > 0)
				$posts[$k]->lockby = $lock->admin_account;

			$posts[$k]->post_level = $this->{$this->model}->get_post_meta($post->post_id, '_cms_post_level', true); // get post level
			$posts[$k]->count_word = str_word_count($post->post_content);
			$posts[$k]->post_create_date = date("d/m/y-H:i", @$this->{$this->model}->get_post_meta($post->post_id, '_cms_post_date_create', true));//
			$posts[$k]->post_update_date = date("d/m/y-H:i", @$this->{$this->model}->get_post_meta($post->post_id, '_cms_post_date_update', true));//
			$posts[$k]->post_publish = date("d/m/y-H:i", @$post->post_time_start);
		}
		
		$render['draw'] = intval($this->input->post('draw'));
		if(isset($this->data['total_post']))
		{
			$total = $this->data['total_post'];
		}
		else
		{

			$condition = array();
			if(isset($search['value']) && $search['value'] != '')
				$condition['search'] = $search['value'];

			if($cat_id && $cat_id >0)
				$condition['category'] = $cat_id_sub;
				$condition['search'] = @$search['value'];

			$total = $this->{$this->model}->condition_query_post_status($post_status)->num($condition);
		}
		$render['recordsFiltered'] = $total;
		$render['recordsTotal'] = $total;
		$render['data'] = json_decode(json_encode($posts), TRUE);
		die(json_encode($render));
	}
	
	function ajax_datatable() {
		$result = array();
		$data = array();
		$query_like = array();
		$query_or_like = array();
		$result['data'] = array();
		$model = $this->model;
		$from = $this->input->get('start');
		$limit = $this->input->get('length');
		$columns = $this->input->get('columns');
		$order = $this->input->get('order');
		$search = $this->input->get('search');
		$request_data = $this->input->get('request_data');

		$cat_id = $this->input->get('cat_id');
		$exclude_postids = $this->input->get('exclude_postids');
		$keyword = $this->input->get('keyword');

		/*foreach($columns as $key =>$column) {
			//search by cols
			if(isset($column['search']['value']) && $column['search']['value'] !='')
			{
				$query_like[$column['data']] = $column['search']['value'];
			}
			//search all cols
			if(isset($search['value']) && $search['value'] != '')
			{
				$query_or_like[$column['data']] = $search['value'];
			}
		}*/
		if(!empty($keyword)){
			$query_like['post_title'] = $keyword;
		}
		if(!empty($search['value'])) {
			$query_like['post_title'] = $search['value'];
		}
		if($cat_id) {
			$post_table = $this->db->dbprefix('posts');
			$term_post_table = $this->db->dbprefix('term_posts');
			$this->$model->join('term_posts',"$post_table.post_id = $term_post_table.post_id");
			$this->$model->where('term_id', $cat_id);
		}

		if($exclude_postids){
			$post_table = $this->db->dbprefix('posts');
			$ex_ids = explode(',', $exclude_postids);
			$this->$model->where_not_in("$post_table.post_id", $ex_ids);
		}
		
		$order_col = $order[0]['column'];
		if(isset($order_col) && isset($columns[$order_col]['data']))
		{
			switch ($columns[$order_col]['data']) {
				case 'post_category':
					$columns[$order_col]['data'] = 'cat_id';
					break;
				case 'date_create':
					$columns[$order_col]['data'] = 'post_time_start';
					break;
				
			}
			$this->$model->order_by($columns[$order_col]['data'], $order[0]['dir']);
		}
		
		if(count($query_like) > 0)
		{
			$this->$model->like($query_like);
		}
		
		if(count($query_or_like) > 0)
		{
			$this->$model->or_like($query_or_like);
		}
		
		if($request_data) {
			if(is_array($request_data))
				$this->$model->where($request_data);
		}

		//Chi loc nhung tin da dang thanh bai viet
		$this->$model->where('post_status', 1);
		
		$this->$model->limit($limit, $from);
		$result['data'] = $this->$model->get_many_by();
		$result['query'] = $this->db->last_query();
		if($result['data'])
		{
			$this->load->model('term_m', 'term');
			foreach($result['data'] as &$post)
			{
				$cats = $this->term->get_the_terms($post->post_id);
				$cats = array_column(json_decode(json_encode($cats), true), 'term_name');
				$post->post_category = implode($cats);

				$post->date_create = date("d/m/y-H:i", $post->post_time_start);
				// $post->post_views = 11;
			}
		}
		$result['draw'] = intval($_GET['draw']);
		if(count($query_like) > 0)
		{
			$this->$model->like($query_like);
		}
		if(count($query_or_like) > 0)
		{
			$this->$model->or_like($query_or_like);
		}
		if($cat_id) {
			$post_table = $this->db->dbprefix('posts');
			$term_post_table = $this->db->dbprefix('term_posts');
			$this->$model->join('term_posts',"$post_table.post_id = $term_post_table.post_id");
			$this->$model->where('term_id', $cat_id);
		}
		//Chi loc nhung tin da dang thanh bai viet
		$this->$model->where('post_status', 1);
		$result['recordsTotal'] = $this->$model->count_all();
		
		$result['recordsFiltered'] =  $result['recordsTotal'];
		die(json_encode($result));
	}

	function ajax_get_meta_post($post_id, $meta_key) {
		
		$this->load->model('term_m', 'term');

		$meta_posts = $this->{$this->model}->get_post_meta($post_id, $meta_key, true);
		$meta_posts = (array)$meta_posts;
		if(!empty($meta_posts)) {
			$meta_posts = $this->{$this->model}->where_in('post_id', $meta_posts)->get_all();
			foreach($meta_posts as $k=>$meta_post) {
				$meta_posts[$k]->post_category = implode(', ', array_column(json_decode(json_encode($this->term->get_the_terms($meta_post->post_id)), true), 'term_name'));
			}
		}
		$result['data'] = $meta_posts;
		$result['draw'] = intval($_GET['draw']);
		$result['recordsTotal'] = count($meta_posts);
		
		$result['recordsFiltered'] =  $result['recordsTotal'];
		die(json_encode($result));
	}

	function ajax_update_meta_post() {

		$post_id = $this->input->post('post_id');
		$meta_key = $this->input->post('meta_key');
		$meta_value = $this->input->post('meta_value');
		
		if(empty($meta_key)) return false;

		$result['status'] = $this->{$this->model}->update_post_meta($post_id, $meta_key, $meta_value);
		die(json_encode($result));
	}

	function ajax_del_meta_post( $post_id = 0, $meta_key = '_cms_post_related_content' ) {
		$this->load->model('term_m', 'term');

		$meta_posts = (array)$this->{$this->model}->get_post_meta($post_id, $meta_key, true);
		prd();
		$post_ids = (array)$this->input->post('post_id');
		$post_ids = array_diff($meta_posts, $post_ids);
		$post_ids = array_unique($post_ids, SORT_NUMERIC);
		$result['data'] = $post_ids;
		$result['status'] = $this->{$this->model}->update_post_meta($post_id, $meta_key, $post_ids);
		die(json_encode($result));
	}

	function ajax_get_posts($term_id = false) {
		if(!is_numeric($term_id)) return false;

		// Lay danh sach post dang chay
		$posts = $this->{$this->model}->get_posts(array('post_status' => 1));
		
		foreach($posts as $k=>$post) {
			$posts[$k]->category = $this->term->get_the_terms($post->post_id);
			$posts[$k]->date_create = $this->{$this->model}->get_post_meta($post->post_id, '_cms_post_date_create', true);
		}
		die(json_encode($posts));
	}

	function ajax_popup_posts( $post_id = 0, $meta_key = '_cms_post_related_content' ) {
		$data['title'] = "Tin liên quan";
		if($meta_key == '_cms_post_most_read')
			$data['title'] = "Tin đọc nhiều nhất";

		$data['post_id'] = $post_id;
		$data['meta_key'] = $meta_key;

		$this->load->model('term_m', 'term');
		// Lay danh sach post dang chay
		$posts = $this->{$this->model}->get_posts(array('post_status' => 1));
		
		foreach($posts as $k=>$post) {
			$posts[$k]->category = $this->term->get_the_terms($post->post_id);
			$posts[$k]->date_create = $this->{$this->model}->get_post_meta($post->post_id, '_cms_post_date_create', true);
		}
		$data['posts'] = $posts;
		$data['menu_tree'] = $this->term->get_menu(0, 'category');

		$meta_posts = $this->{$this->model}->get_post_meta($post_id, $meta_key, true);
		$meta_posts = (array)$meta_posts;
		if(!empty($meta_posts)) {
			//$meta_posts = unserialize($meta_posts);
			$meta_posts = $this->{$this->model}->where_in('post_id', $meta_posts)->get_all();
			foreach($meta_posts as $k=>$meta_post) {
				$meta_posts[$k]->category = json_decode(json_encode($this->term->get_the_terms($meta_post->post_id)), true);
			}
		}
		$data['meta_posts'] = $meta_posts;
		//die(var_dump($meta_posts));
		$template = $this->template->tpl_prefix_admin."posts/popup_add_posts";
		echo $this->load->view($template, $data, TRUE);
		die();
	}

	function ajax_add_posts( $post_id = 0, $meta_key = '_cms_post_related_content' ) {
		$this->load->model('term_m', 'term');

		$meta_posts = $this->{$this->model}->get_post_meta($post_id, $meta_key, true);

		$post_ids = $this->input->post('post_id');
		$post_ids = array_merge((array)$meta_posts, (array)$post_ids);
		$post_ids = json_decode(json_encode($post_ids), TRUE);
		$post_ids = array_unique($post_ids, SORT_NUMERIC);
		//$post_ids = serialize($post_ids);
		$result['data'] = $post_ids;
		$result['status'] = $this->{$this->model}->update_post_meta($post_id, $meta_key, $post_ids);
		die(json_encode($result));
	}

	function ajax_create_slug() {
		$title = $this->input->post('title', TRUE);
		if($title == '') die();
		$post_id = $this->input->post('post_id', TRUE);
		$slug = create_slug($title);
		if($post_id)
		{
			$this->{$this->model}->update($post_id, array('post_slug'=>$slug, 
				'post_title'=>$title));		
		}
		die($slug);
	}
	
	function ajax_upload($post_id = 0){
		require(APPPATH.'libraries/FileUpload.php');
		$this->load->model('simage');
		$post = $this->_model->get($post_id);
		if(!$post) die('Post id not found');
		$uploader = new FileUpload('post_thumb');
		$this->folder_upload = "images/posts/".$this->admin->account.'/thumb'.'/';
		if($post_id <=0) die();
		$this->simage->create_dirs($this->folder_upload);
		
		$uploader->allowedExtensions = array('jpg', 'jpeg', 'png', 'gif','swf');
		$uploader->sizeLimit = 91071520;
		$uploader->newFileName = $post->post_slug.'-'.$post_id.'.'.$uploader->getExtension();
		$result = $uploader->handleUpload('./'.$this->folder_upload);
		if (!$result) {
			echo json_encode(array(
				'success' => false,
				'msg' => $uploader->getErrorMsg()
				));    
			
		} else {
			if(!is_array($post_id)) {
				
				$this->_model->update($post_id, array(
					'post_thumb' => $this->folder_upload.''.$uploader->getFileName(),
					));
				$this->simage->cache($this->folder_upload.''.$uploader->getFileName());
			}
			
			echo json_encode(array(
				'success' => true,
				'file' => base_url().$this->folder_upload.''.$uploader->getFileName()."?v=".time(),
				));
			
		}
	}

	function popup_post_images($edit_id) {
		$this->{$this->model}->select('post_content_image');
		$edit_data = $this->{$this->model}->get_post($edit_id);
		if(!$edit_data) {
			$this->messages->add('Bài viết không tồn tại','error');
			redirect($this->url_index);
		}

		$action = $this->input->post('action');
		if($action) switch ($action) {
			case "select":
				//Get info image
				$image_id = $this->input->post('image_id');
				$post_content_image = maybe_unserialize($edit_data->post_content_image);
				foreach($post_content_image as $tmp) {
					if($tmp['id'] == $image_id)
						exit(json_encode($tmp));
				}
				exit("[]");
			break;
			
			case "delete":
				$ids = $this->input->post('data');
				$post_content_image = maybe_unserialize($edit_data->post_content_image);
				foreach($post_content_image as $k=>$tmp) {
					if(in_array($tmp['id'], $ids))
						unset($post_content_image[$k]);
				}

				$post_content_image = maybe_serialize($post_content_image);
				$this->{$this->model}->update($edit_id, array('post_content_image' => $post_content_image, 'post_type' => 2), TRUE);
				exit(json_encode($post_content_image));
			break;
			
			case "update":
				$image_id = $this->input->post('image_id');
				$caption = $this->input->post('caption');
				$post_content_image = maybe_unserialize($edit_data->post_content_image);
				foreach($post_content_image as $k=>$tmp) {
					if($tmp['id'] == $image_id)
						$post_content_image[$k]['caption'] = $caption;
				}
				$post_content_image = maybe_serialize($post_content_image);
				$this->{$this->model}->update($edit_id, array('post_content_image' => $post_content_image, 'post_type' => 2), TRUE);
				exit();
			break;
			
			case "insert":
				$url = $this->input->post('url');
				if(empty($url)) exit('');
				$post_content_image = maybe_unserialize($edit_data->post_content_image);
				$ids = array(0);
				if(!empty($post_content_image))
					$ids = array_column($post_content_image, 'id');
				$newItem = array(
					'id' => max($ids) + 1,
					'fullPath' => $url,
					'caption' => ''
				);
				$post_content_image[] = $newItem;
				$post_content_image = maybe_serialize($post_content_image);
				$this->{$this->model}->update($edit_id, array('post_content_image' => $post_content_image, 'post_type' => 2), TRUE);
				echo $this->load->view('admin/posts/partial_image', array('item' => $newItem), TRUE);
				exit();
			break;
			
			case "sortable":
				$data = $this->input->post('data');
				if(empty($data)) exit('');
				$post_content_image = maybe_unserialize($edit_data->post_content_image);
				$new_content = array();
				foreach($post_content_image as $image) {
					$key = array_search($image['id'], $data);
					$new_content[$key] = $image;
				}
				ksort($new_content);
				$post_content_image = maybe_serialize($new_content);
				$this->{$this->model}->update($edit_id, array('post_content_image' => $post_content_image, 'post_type' => 2), TRUE);
				exit(json_encode($data));
			break;

			default:
			break;
		}

		$result = maybe_unserialize($edit_data->post_content_image);
		if($result === null || !is_array($result)) {
			$result = array();
		}
		$this->data['listImg'] = $result;
		$this->data['edit_id'] = $edit_id;

		$template = $this->template->tpl_prefix_admin."posts/popup_post_images_bkkhanh";
		echo $this->load->view($template, $this->data, TRUE);
		die();
	}

}
